package ngat.oss;

import ngat.phase2.*;
import ngat.phase2.nonpersist.*;
import ngat.util.*;
import ngat.util.logging.*;
import ngat.astrometry.*;
import ngat.instrument.*;

import jyd.dbms.*;
import jyd.storable.*;
import jyd.collection.*;

import java.io.*;
import java.util.*;
import java.text.*;

public class TestGroupWindow {

public static final String CLASS = "TestGroupWindow";

public static final String DB_NAME = "LT_Phase2_001";

public static final String DB_DIR = "/space/home/dev/bin/oss/java";

public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");

public static SimpleTimeZone UTC = new SimpleTimeZone(0, "UTC");

public static final double LAT = Math.toRadians(53.0);

public static final double LON = Math.toRadians(-3.0);

public static void main(String args[]) {
    new TestGroupWindow().exec();
}

public void exec() {
    sdf.setTimeZone(UTC);

    File dbDir = new File(DB_DIR);
    OSS_Utilities.setDatabaseDir(dbDir);
    OSS_Utilities.setRootName(DB_NAME);
    File dbFile = new File(DB_DIR, "phase2.s0");

    Logger logger = LogManager.getLogger("TEST");
    logger.setLogLevel(Logging.ALL);
    
    LogHandler console = new ConsoleLogHandler(new SimpleLogFormatter());
    console.setLogLevel(Logging.ALL);

    logger.addHandler(console);

    Position.setViewpoint(LAT, LON);
    
    Position moon = Astrometry.getLunarPosition();
    long moonset  = 0L;
    long moonrise = 0L;
    long estart = 0L;
    long lend   = 999999999999999L;
    long now = System.currentTimeMillis();

    if (moon.isRisen()) {
	// Sets an earliest start for ALL obs.
        moonset  = now + (long)moon.getUpTimeMillis();
	estart = moonset;
	logger.log(1, CLASS, "-", "exec", 
		   "Moon is currently UP, sets at "+sdf.format(new Date(moonset))); 	
    } else { 
	// Sets a latest end for ALL obs.
	moonrise = now + (long)moon.getDownTimeMillis();   
	lend = moonrise;
	logger.log(1, CLASS, "-", "exec", 
		   "Moon is currently DOWN, rises at "+sdf.format(new Date(moonrise)));
    }

    try {
	
	Transaction t = Transaction.current();
	
	Root root = OSS_Utilities.fetchRoot();
	
	// Check it exists.
	if (root == null) {		
	    logger.log(1, CLASS, "-", "exec", 
		       "Root: Not in database.");
	    return;
	} 
			
	Iterator iTag = root.listAllTags();
	while (iTag.hasNext()) {
	    
	    Tag tag = (Tag)iTag.next();
	    
	    Iterator iUser = tag.listAllUsers();
	    while (iUser.hasNext()) {
		
		User user = (User)iUser.next();

		Iterator iProp = user.listAllProposals();
		while (iProp.hasNext()) {

		    KVPair pair = (KVPair)iProp.next();
		    String name = (String)pair.getKey();
		    Path   path = new Path(user.getFullPath(), name);
		    Proposal proposal = null;
		    try {
			proposal = OSS_Utilities.fetchProposal(path);
		    } catch (IOException iox) {
			System.err.println("Proposal: "+path.toString()+
					   " Error fetching from Database: "+iox);	
			continue;
		    }		
		   
		    Iterator iGroup = proposal.listAllGroups();
		    while (iGroup.hasNext()) {
			
			StringBuffer buff = new StringBuffer();

			Group group = (Group)iGroup.next();
			long start = estart;
			long end   = lend;
			
			buff.append("Doing Group: "+group.getFullPath());
			
			long expires = group.getExpiryDate();

			buff.append("\n\tExpiry date: "+sdf.format(new Date(expires)));
			
			buff.append("\n\tMax completion by: "+
				    sdf.format(new Date(now + (long)group.getMaximalExecutionTime())));
			
			Iterator it = group.listAllObservations();
			
			while (it.hasNext()) {	 			   
			    Observation observation = (Observation)it.next();
			    buff.append("\n\tObservation: "+observation.getName());
			    Source   source = observation.getSource();
			    Position target = source.getPosition(); 
			    buff.append("\n\t\tTarget: "+target.toString());
			    long targset  = 0L;
			    long targrise = 0L;
			    if (target.isRisen()) {
				targset  = now + (long)target.getUpTimeMillis();				
				buff.append("\n\t\tCurrently UP,   SETS:  "+sdf.format(new Date(targset))); 
				if (targset < end)
				    end = targset;
			    } else { 
				targrise = now + (long)target.getDownTimeMillis();       			      
				buff.append("\n\t\tCurrently DOWN, RISES: "+sdf.format(new Date(targrise)));
				if (targrise > start)
				    start = targrise;
			    }
			   
			} 
			if (start > end)
			    buff.append("\n\tNO WINDOW AVAILABLE");
			else
			    buff.append("\n\t**** Window FROM: "+
					sdf.format(new Date(start))+
					" TO: "+sdf.format(new Date(end)));
			System.err.println(buff.toString());
		    }
		}
	    }
	}
    } catch (Exception e) {
	logger.log(1, CLASS, "-", "exec", "Exception: "+e);
	return;
    }
}
}
